package main

import (
    "context"
    log "github.com/sirupsen/logrus"
    "net/http"
    "os"
    "os/signal"
    "time"
    "github.com/gin-gonic/gin"
)


func CORS() gin.HandlerFunc {
    return func(context *gin.Context) {
        context.Writer.Header().Add("Access-Control-Allow-Origin", context.Request.Header.Get("Origin"))
        context.Writer.Header().Set("Access-Control-Max-Age", "86400")
        context.Writer.Header().Set("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE, UPDATE, PATCH")
        context.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Apitoken")
        context.Writer.Header().Set("Access-Control-Expose-Headers", "Content-Length")
        context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
        if context.Request.Method == "OPTIONS" {
            context.AbortWithStatus(200)
        } else {
            context.Next()
        }
    }
}


func main() {
    log.SetLevel(log.DebugLevel)
    log.SetFormatter(&log.JSONFormatter{})
    router := gin.Default()
    router.Use(CORS())
    router.GET("/", func(c *gin.Context) {
        log.Debugf("aaaaaaaaaaaa")
        c.Writer.Header().Set("username","lynzhang")
        c.String(http.StatusOK, "Welcome Gin Server")
    })

    srv := &http.Server{
        Addr:    ":8090",
        Handler: router,
    }

    go func() {
        // service connections
        if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
            log.Fatalf("listen: %s\n", err)
        }
    }()

    // Wait for interrupt signal to gracefully shutdown the server with
    // a timeout of 5 seconds.
    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt)
    <-quit
    log.Println("Shutdown Server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
    log.Println("Server exiting")
}
